<template>
  <div class="OrgBasicInfo-container">
    <a-form-model ref="ruleForm" :model="formInfo" :rules="rules">
      <a-row :gutter="24">
        <a-col :md="8" :sm="8">
          <a-form-model-item
            label="上级组织"
            :class="formInfo.parentId && type !== 'look' ? 'parentId' : ''"
            :prop="parent ? 'parentId' : ''"
            :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
            :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
          >
            <a-spin :spinning="treeLoading">
              <a-tree-select
                :disabled="type === 'look' || !formInfo.parentId"
                v-model="formInfo.parentId"
                :defaultExpandedKeys="recordId"
                :treeData="highUpsOrgs"
                :replaceFields="{ title: 'name', key: 'id', value: 'id' }"
                :placeholder="formInfo.parentId ? '请选择上级组织' : '无'"
              />
            </a-spin>
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="8">
          <a-form-model-item label="组织名称" prop="name" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <a-input :disabled="type === 'look' || !formInfo.parentId" v-model="formInfo.name" placeholder="请输入组织名称"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="8">
          <a-form-model-item label="组织编码" prop="code" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <a-input :disabled="type === 'look' || disabledTag" v-model="formInfo.code" placeholder="请输入组织编码"></a-input>
            <!-- <a-input :disabled="formInfo.code === 'PD' && (type === 'look' ||  type === 'edit')" v-model="formInfo.code" placeholder="请输入组织编码"></a-input> -->
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="8">
          <a-form-model-item label="组织类型" prop="type" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <a-select :disabled="type === 'look' || disabledTag" v-model="formInfo.type" placeholder="请选择" @change="typechange(formInfo.type)">
              <a-select-option v-for="item in typeList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <!-- 1104版本更改 -->
        <a-col :md="8" :sm="8" v-if="tagCodeActive || formInfo.tagCode !== ''">
          <a-form-model-item label="组织标签" prop="tagCode" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <a-select :class="type !== 'look' ? 'tagCode' : ''" :disabled="type === 'look' || disabledTag" v-model="formInfo.tagCode" placeholder="请选择">
              <a-select-option v-for="item in tagCodeList" :key="item.id" :value="item.code">{{ item.name }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="8">
          <a-form-model-item label="排序号" prop="sortNum" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <a-input-number :min="0" :precision="0" :disabled="type === 'look'" v-model="formInfo.sortNum" placeholder="请输入"></a-input-number>
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="8">
          <a-form-model-item label="状态" prop="enable" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <a-select placeholder="请选择" v-model="formInfo.enable" :disabled="type === 'look'">
              <a-select-option v-for="(item, index) in state" :value="item.value" :key="index">{{ item.name }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :md="16" :sm="16">
          <a-form-model-item label="分管领导" prop="leader" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <a-tree-select
              multiple
              v-model="formInfo.leader"
              :disabled="type === 'look'"
              :treeData="leaderTree"
              :treeDefaultExpandedKeys="leaderExpandedKeys"
              placeholder="请选择分管领导"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :replaceFields="{ key: 'id', value: 'id' }"
              :load-data="onLoadLeaderData"
              treeNodeLabelProp="label"
            >
              <a-icon v-if="leaderLoading" slot="suffixIcon" type="loading" />
            </a-tree-select>
          </a-form-model-item>
        </a-col>

        <a-col :md="24" :sm="24">
          <a-form-model-item label="描述" prop="description" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <BaseTextarea :disabled="type === 'look'" v-model="formInfo.description" placeholder="请输入描述" :auto-size="{ minRows: 3, maxRows: 6 }" />
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <searchJob :visible="visibleState.searchJob" @handleCancel="visibleState.searchJob = false" @handleOk="handleOk"></searchJob>
  </div>
</template>

<script>
import { getEditPost, addOrgList, editOrgListNew, getJobDetails, addOrgByTemplateNew, findOrgTagList } from '@/api/system/system'
import searchJob from './searchJob' // 绑定组织
import { typeList } from './model.js'
import { getCustOrgTree, getJobs } from '@/api/subassembly/TreeSelectOrganization'
import { generateList, findNodeFromTree } from '@/utils/util'

export default {
  name: 'OrgBasicInfo',
  components: {
    searchJob
  },
  props: {
    recordId: {
      type: String,
      default: ''
    },
    parentId: {
      type: String,
      default: ''
    },
    parent: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: ''
    },
    disabledTag: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      //状态
      state: [
        {
          name: '可用',
          value: 1
        },
        {
          name: '不可用',
          value: 0
        }
      ],
      visibleState: {
        searchJob: false
      },
      highUpsOrgs: [], //上级组织信息
      treeDefaultExpandedKeys: [],
      //表单数据
      formInfo: {
        parentId: '',
        orgId: '',
        code: '',
        // joblabel: '',
        leader: [],
        type: '',
        enable: null,
        tagCode: ''
      },
      rules: {
        parentId: [{ required: true, message: '请选择上级组织', trigger: 'change' }],
        name: [{ required: true, message: '请填写组织名称', trigger: 'blur' }],
        code: [{ required: true, message: '请填写组织编码', trigger: 'blur' }],
        type: [{ required: true, message: '选择组织类型', trigger: 'blur' }],
        tagCode: [{ required: true, message: '选择组织标签', trigger: 'change' }],
        enable: [{ required: true, message: '选择状态', trigger: 'change' }]
      },
      typeList: typeList,
      parentOrgInfo: {},
      tagCodeList: [], //组织标签列表
      tagCodeActive: false, //是否展示组织机构
      leaderTree: [], //分管领导树
      leaderExpandedKeys: [],
      leaderLoading: false,
      treeLoading: false
    }
  },
  watch: {
    'formInfo.type': {
      immediate: true,
      handler(val) {
        this.$emit('orgTypeChanged', val)
      }
    }
  },
  methods: {
    onLoadLeaderData({ dataRef }) {
      return new Promise((resolve) => {
        if (dataRef?.data?.type == 2 || dataRef?.data?.type == 7) {
          getJobs({
            orgId: dataRef.id,
            resultWithEmployee: false
          }).then((res) => {
            if (this.leaderLoading) this.leaderLoading = false
            if (res.status == 200) {
              dataRef.children = res.data.map((item) => ({
                data: {
                  ...item,
                  parentId: item.orgId
                },
                id: item.id,
                label: item.name,
                pid: item.pid,
                type: item.type,
                isLeaf: true
              }))
              this.formInfo.leader.forEach((id) => {
                this.leaderExpandedKeys = this.leaderExpandedKeys.concat(this.findParentIds(this.leaderTree, id))
              })
              this.$forceUpdate()
            }
            resolve()
          })
        } else {
          resolve()
        }
      })
    },
    findParentIds(treeData, id, config = { parentKey: 'parentId', key: 'id' }) {
      const ids = []
      const list = generateList(treeData)
      const fun = (parentId) => {
        const findItem = list.find((item) => item.id === parentId || item.data?.id === parentId)
        if (findItem) {
          ids.push(findItem.id || findItem.data?.id)
          if (findItem.parentId || findItem.data?.parentId) {
            fun(findItem.parentId || findItem.data?.parentId)
          }
        }
      }
      fun(id)
      return ids
    },
    /**
     * 过滤上级组织
     * **/
    filterParentOrgs(treeData) {
      if (!this.recordId) return treeData
      const node = findNodeFromTree(treeData, { key: 'id', value: this.recordId })
      if (!node) return treeData
      const fun = (list) => {
        list.forEach((item) => {
          item.disabled = true
          if (!!list.children && !!list.children.length) {
            fun(item.children)
          }
        })
      }
      node.disabled = true
      if (!!node.children && !!node.children.length) {
        fun(node.children)
      }
      return treeData
    },
    /**
     * 过滤分管领导
     * **/
    filterLeaderTree(treeData, titlePath) {
      return treeData.map((item) => {
        let label = titlePath ? `${titlePath}/${item.label}` : item.label
        if (item.children && item.children.length) {
          return {
            ...item,
            disabled: true,
            title: item.label,
            label,
            children: this.filterLeaderTree(item.children, label)
          }
        } else {
          return {
            ...item,
            title: item.label,
            label,
            disabled: true
          }
        }
      })
    },
    //获取组织架构
    getOrgTree() {
      // 上级组织树
      this.formInfo.parentId = this.parentId
      this.treeLoading = true
      getCustOrgTree({
        baseOrgType: 1,
        orgDeptTagCodeAll: 1,
        enable: 1,
        containVirtual: null
      }).then((res) => {
        if (res.status == 200) {
          this.highUpsOrgs = this.filterParentOrgs(res.data)
        }
        this.treeLoading = false
      })
    },
    /**
     *
     * 禁用树节点
     * **/
    disabledNode(tree) {
      tree.forEach((item) => {
        if (this.recordId === item.id) {
          item.disabled = true
        }
        if (item.children && item.children.length) {
          this.disabledNode(item.children)
        }
      })
    },
    //组织类型改变
    async typechange(type) {
      if (type == 1 || type == 3) {
        let res = await findOrgTagList(type)
        if (res?.data?.length > 0) {
          this.tagCodeList = res.data
        }
        this.tagCodeActive = true
        return
      }
      this.tagCodeActive = false
      this.formInfo.tagCode = ''
      console.log('this.tagCodeList', this.tagCodeList)
    },
    //清空表单数据
    clearFrom() {
      this.$refs.ruleForm.resetFields()
      this.formInfo.tagCode = ''
    },
    async handleSubmit(...args) {
      const [resolve, reject] = args
      console.log('this.parentId', this.parentId)
      await this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) {
          reject && reject()
          return
        }
        let params = {
          ...this.formInfo,
          id: this.recordId
        }
        params.leader = this.formInfo.leader ? this.formInfo.leader.join(',') : this.formInfo.leader
        const fn = this.recordId ? editOrgListNew : addOrgByTemplateNew
        const res = await fn(params)
        if (res.data && !res.data.msg) {
          this.$message.success('提交成功')
          this.$emit('update:recordId', res.data.id)
        } else {
          this.$message.error(res.data.msg)
          return
        }
        resolve()
      })
    },
    // /**
    //  *  获取部门分管领导信息
    //  */
    // async getJobDetailsReq(leaderId) {
    //   try {
    //     const params = {
    //       id: leaderId
    //     }
    //     const res = await getJobDetails(params)
    //     this.formInfo.joblabel = res.data.pname
    //   } catch (e) {
    //     console.error(e)
    //   }
    // },
    /**
     * 获取组织基本信息的详情
     */
    async getEditPostReq(id, onlyParent = false) {
      try {
        const leader = await getCustOrgTree({
          baseOrgType: 1,
          orgDeptTagCodeAll: 1,
          enable: 1,
          containVirtual: null
        })
        if (leader.status == 200) {
          this.leaderTree = this.filterLeaderTree(leader.data)
          console.log(this.leaderTree)
        }
        if (!id) return
        this.leaderLoading = true
        const res = await getEditPost({ id })
        if (onlyParent) {
          this.parentOrgInfo = res.data || {}
        } else {
          this.formInfo = {
            ...this.formInfo,
            ...res.data
          }

          this.formInfo.leader = !!this.formInfo.leader ? this.formInfo.leader.split(',') : []
          this.formInfo.pastOrgIds = !!this.formInfo.pastOrgIds ? this.formInfo.pastOrgIds.split(',') : []
          this.typechange(this.formInfo.type)
          if (this.formInfo.pastOrgIds && !!this.formInfo.pastOrgIds.length) {
            this.formInfo.pastOrgIds.forEach((id) => {
              this.onLoadLeaderData({
                dataRef: findNodeFromTree(this.leaderTree, { key: 'id', value: id })
              })
            })
          }
        }
      } catch (e) {
        this.leaderLoading = false
        console.error(e)
      }
      this.$emit('typeChange', this.formInfo.type)
    },
    handleOk(e) {
      this.visibleState.searchJob = false
    }
  }
}
</script>

<style lang="less" scoped>
.tagCode {
  /deep/.ant-select-selection {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
}
/deep/.ant-select-disabled {
  .ant-select-selection
  {
    border-color: #d9d9d9 !important;
  background-color: #f5f5f5 !important;
  }
  
}
.parentId {
  /deep/.ant-select-selection {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
}
</style>
